<template>
  <div class="wrap">
    <DaoHangLan></DaoHangLan>
    <van-index-bar
      highlight-color="#1989fa"
      :index-list="indexList">
      <div>
        <div>&emsp;当前定位</div>
        <div>&emsp;上海</div>
      </div>
      <div v-for="item in filterData" :key="item.letter">
        <van-index-anchor :index="item.letter"></van-index-anchor>
        <div
          class="content"
          v-for="row in item.list"
          :key="row.value">&emsp;{{row.label}}</div>
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import DaoHangLan from '@/components/DaoHangLan'
import { getcity } from '@/api/getcity'
export default {
  components: {
    DaoHangLan
  },
  name: 'CitySelect',
  data () {
    return {
      indexList: [], // 索引字符
      filterData: [] // 处理后的 待渲染数据
    }
  },
  methods: {
    async getCityList () {
      const res = await getcity()
      console.log('城市列表', res.body)
      const mapData = res.body
      // 安装使用 js-pinyin 插件，获取待处理字段的拼音
      const pinyin = require('js-pinyin')
      mapData.forEach(item => { item.pinyin = pinyin.getFullChars(item.label) })

      const provice = {}
      mapData.forEach((item) => {
        const Initials = item.pinyin[0].toUpperCase()
        // 如果对象里有当前字母项则直接 push 一个对象,如果没有则创建一个新的键并赋值;
        if (provice[Initials]) {
          provice[Initials].push(item)
        } else {
          provice[Initials] = [item]
        }
      })
      // 将数据转为数组，并按字母顺利排列
      this.filterData = []
      for (const key in provice) {
        const obj = { letter: key, list: provice[key] }
        this.filterData.push(obj)
      }
      this.filterData.sort((a, b) => { return a.letter.localeCompare(b.letter) })
      // 为索引字符数组赋值
      this.indexList = []
      this.filterData.forEach(item => this.indexList.push(item.letter))
      console.log('filterData', this.filterData)
    }
  },
  mounted () {
    this.getCityList()
  }
}
</script>

<style lang="less" scoped>
.content{
  font-size: 15px;
  padding: 6px 0;
  border-bottom: 1px solid #eeeeee;
}
</style>
